<template>
  <div>
    <div>
      <BaseTable
        class="mt-2"
        :loading="loading"
        row-key="id"
        column-code="000738"
        :data-source="tableData"
        :pagination="pagination"
        :custom-row="(record) => ({ onClick: () => onSelectRow(record) })"
        :row-class-name="(record) => (record.id === selectRow.id ? 'selected-row' : '')"
        fill
        :extra-height="300"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'execNurseStatus'">
            <!-- execStatus：执行状态  0：待执行(非药品) 1：已执行 2：待执行（已发药）3：已退药 4：退药中   -->
            <a-tag v-if="record.execStatus === 0" color="blue">待执行</a-tag>
            <a-tag v-if="record.execStatus === 2" color="blue">待执行</a-tag>
            <a-tag v-if="record.execStatus === 1" color="success">已执行</a-tag>
            <a-tag v-if="record.execStatus === 3" color="green">已退药</a-tag>
            <a-tag v-if="record.execStatus === 4" color="red">退药中</a-tag>
          </template>
          <template v-if="column.dataIndex === 'children'">
            <DoctorAdviceOrder
              :row-data="record"
              :params-key="{
                mc: 'adv.mc',
                gg: 'adv.gg',
                sl: 'clinicalDose',
                dw: 'adv.jldw',
                yf: 'deliverRoute.fyff',
                pl: 'fqy.plId',
                drugPathName: 'drugPathName'
              }"
            />
          </template>

          <div v-if="column.dataIndex === 'yzzxlb'">
            {{ record.yzzxlb == 0 ? '临时' : '长期' }}
          </div>
        </template>
      </BaseTable>
    </div>
    <BaseTable
      class="mt-2"
      :loading="loading1"
      row-key="id"
      column-code="000107"
      :data-source="dataSource"
      :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      height="180"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'advTypeCode'">
          <EditCell>
            <a-select
              v-model:value="record.advTypeCode"
              :disabled="!record.isNew"
              :virtual="false"
              :options="options"
              placeholder="请选择"
              @change="(data) => onChangeClassify(data, record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'advName'">
          <EditCell>
            <SelectTable
              v-model:value="record.advName"
              :disabled="!record.isNew"
              type="补记账"
              :search-params="{ xmlbbh: ['3', '7', '8', '30', '99'] }"
              :auto-focus="record.isNew && focusCell === record.key + '处置'"
              @select="(data) => onSelectTable(data, record)"
            />
          </EditCell>
        </template>
        <template v-if="column.dataIndex === 'count'">
          <EditCell>
            <BaseInput
              v-model:value="record.count"
              v-input:float.3
              :disabled="!record.isNew"
              :auto-focus="record.isNew && focusCell === record.key + '数量'"
              class="text-right"
              placeholder="请输入"
              @keydown.enter="addRow()"
              @blur="editRow(record)"
            />
          </EditCell>
        </template>
        <div v-if="column.dataIndex === 'amount'">
          <div v-if="record.isNew">{{ formatAmount(record.price * record.count) }}</div>
          <div v-else>{{ formatAmount(record.amount) }}</div>
        </div>
        <div v-if="column.dataIndex === 'memo'">
          <EditCell>
            <BaseInput v-model:value="record.memo" :disabled="!record.isNew" placeholder="请输入" @blur="editRow(record)" />
          </EditCell>
        </div>
        <template v-if="column.dataIndex === 'xh'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'action'">
          <BaseButton
            confirm-text="确认删除？"
            :disabled="empId !== record.accountEmpId || selectedItem.status !== 0 || selectedItem.chargeStatus !== 0"
            type="text"
            danger
            size="small"
            @click="onDelete(record)"
            >删除</BaseButton
          >
        </template>
      </template>
      <template #footer>
        <div class="text-center sticky bottom-0">
          <a-button class="mr-2" :disabled="!selectRow.id || selectedItem.status !== 0 || selectedItem.chargeStatus !== 0" @click="addRow()">
            新增一条
          </a-button>
          <a-button type="primary" :disabled="!selectRow.id || selectedItem.status !== 0 || selectedItem.chargeStatus !== 0" @click="saveNewRows()">
            保存入账
          </a-button>
        </div>
      </template>
    </BaseTable>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { formatAmount } from '@/utils/format.js'
import useUserStore from '@/store/user'

const props = defineProps({
  selectedItem: {
    type: Object,
    default: () => ({})
  },
  formState: {
    type: Object,
    default: () => ({})
  }
})

const { empId } = useUserStore()
const selectRow = ref({})
const focusCell = ref('')
const options = ref([])

const { tableData, getData, pagination, loading } = useTable({
  url: '/inp/clinicalOrder/getClinicalOrderExecuteList',
  immediate: false,
  formatParams: () => {
    return {
      inplsh: props.selectedItem.inplsh,
      pyjm: props.formState.pyjm,
      accountTime: props.formState.timeType === 0 ? undefined : dayjs().format('YYYY-MM-DD'),
      advOrderType: 2,
      showAllAdvice: true
    }
  },
  onSuccess: () => {
    selectRow.value = {}
    dataSource.value = []
  }
})
const {
  loading: loading1,
  tableData: dataSource,
  getData: getBookData
} = useTable({
  url: '/inp/inpComprehensive/getInpExpensesList',
  immediate: false,
  pagination: true,
  formatParams: () => {
    return {
      inplsh: props.selectedItem.inplsh,
      lastDeptCode: props.selectedItem?.aptmDeptCode,
      advExecId: selectRow.value.id,
      // status: 0,
      accountType: props.formState.accountType
    }
  }
})
const onSelectRow = (select) => {
  selectRow.value = select
  getBookData()
}
const getProjectList = async () => {
  const { code, data } = await post('/drugStorage/comprehenive/getMedicalProjectList_BJZ')
  if (code !== 0) return
  options.value = data.map((item) => {
    return {
      label: item.mc,
      value: item.bh.toString()
    }
  })
  options.value.unshift({ label: '全部', value: '' })
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = {
    key,
    isNew: true,
    advTypeName: '',
    advTypeCode: '',
    inplsh: props.selectedItem.inplsh,
    deptCode: props.selectedItem.aptmDeptCode,
    advExecId: selectRow.value.id,
    accountType: props.formState.accountType
  }
  dataSource.value.push(addRow)
  focusCell.value = key + '处置'
}
const onSelectTable = (medicine, row) => {
  row.advName = medicine.mc
  row.advCode = medicine.bh
  row.price = medicine.dj
  row.unit = medicine.dw || '次'
  focusCell.value = row.key + '数量'
}
const saveNewRows = () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.count) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}
//修改行
const editRow = (row) => !row.isNew && fetchSave(row)
// 保存行
const fetchSave = async (row) => {
  const { code, msg } = await post('/inp/inpComprehensive/doSaveInpExpenses', row)
  if (code !== 0) return message.error(msg || '操作失败')
  getBookData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
//删除行
const onDelete = async (row) => {
  if (!row.isNew) {
    const { code, msg } = await post('/inp/inpComprehensive/doDelInpExpenses', {
      id: row?.id
    })
    if (code !== 0) return message.error(msg || '删除失败')
    message.success(msg)
    getBookData()
  } else {
    dataSource.value = dataSource.value.filter((item) => {
      return item.key !== row.key
    })
    message.success('删除成功')
  }
}
//分类
const onChangeClassify = (data, record) => {
  options.value.forEach((item) => {
    if (item.value === data) {
      if (item.label === '全部') {
        record.advTypeName = ''
      } else {
        record.advTypeName = item.label
      }
    }
  })
  record.advName = ''
  record.advCode = ''
  record.price = ''
  record.unit = ''
  focusCell.value = record.key + '处置'
}

watch(
  () => props.selectedItem.inplsh,
  (val) => {
    if (val) getData()
  }
)
onMounted(() => {
  getProjectList()
})

defineExpose({
  getData
})
</script>
